package com.zcy.util;

import com.espertech.esper.common.client.EPCompiled;
import com.espertech.esper.common.client.configuration.Configuration;
import com.espertech.esper.common.client.fireandforget.EPFireAndForgetPreparedQuery;
import com.espertech.esper.common.client.fireandforget.EPFireAndForgetPreparedQueryParameterized;
import com.espertech.esper.common.client.fireandforget.EPFireAndForgetQueryResult;
import com.espertech.esper.compiler.client.CompilerArguments;
import com.espertech.esper.compiler.client.EPCompileException;
import com.espertech.esper.compiler.client.EPCompilerProvider;
import com.espertech.esper.runtime.client.EPRuntime;
import com.espertech.esper.runtime.client.EPRuntimeOptions;
import com.espertech.esper.runtime.client.EPRuntimeProvider;

/**
 * It is very important.
 * 只要runtime的url相同（下述方法中runtime的名称为'default'）则runtime就为同一个对象，runtime中包含的configuration的配置也会共享
 * 详见源码：{@link EPRuntimeProvider#getRuntime(String, Configuration, EPRuntimeOptions)}
 */
public class EsperFireForget {

    private static EPFireAndForgetPreparedQuery preparedQuery;

    public EPCompiled compileQuery(String query) {
        EPRuntime runtime = EPRuntimeProvider.getDefaultRuntime();

        CompilerArguments arguments = new CompilerArguments();
        arguments.getPath().add(runtime.getRuntimePath());

        try {
            return EPCompilerProvider.getCompiler().compileQuery(query, arguments);
        } catch (EPCompileException e) {
            throw new RuntimeException(e);
        }
    }

    public EPFireAndForgetQueryResult executeQuery(EPCompiled epCompiled) {
        return EPRuntimeProvider.getDefaultRuntime().getFireAndForgetService().executeQuery(epCompiled);
    }

    public EPFireAndForgetQueryResult prepareQuery(EPCompiled epCompiled) {
        if (preparedQuery == null) {
            preparedQuery = EPRuntimeProvider.getDefaultRuntime().getFireAndForgetService().prepareQuery(epCompiled);
        }
        return preparedQuery.execute();
    }

    public PrepareWithQueryResult prepareQueryWithParameters(PrepareWithQueryResult prepareWithQueryResult) {
        if (prepareWithQueryResult.getPrepared() == null) {
            EPFireAndForgetPreparedQueryParameterized preparedQueryParameterized = EPRuntimeProvider.getDefaultRuntime().getFireAndForgetService().prepareQueryWithParameters(prepareWithQueryResult.getEpCompiled());
            // 为了代码开发便利，初次执行，设置参数为0L
            preparedQueryParameterized.setObject(1, 0L);
            prepareWithQueryResult.setPrepared(preparedQueryParameterized);
        }

        EPFireAndForgetQueryResult epFireAndForgetQueryResult = EPRuntimeProvider.getDefaultRuntime().getFireAndForgetService().executeQuery(prepareWithQueryResult.getPrepared());

        prepareWithQueryResult.setResult(epFireAndForgetQueryResult);
        return prepareWithQueryResult;
    }
}

